package com.geng.demo.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {

    private static final Logger logger = LogManager.getLogger(WechatUtil.class);

    public String sendAppMessage(String accessToken, String message) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        try {
            // 发送 HTTP POST 请求
            String response = sendHttpPostRequest(url, message);

            // 解析返回的 JSON
            JSONObject jsonResponse = new JSONObject(response);
            int errcode = jsonResponse.getInt("errcode");

            // 判断 access_token 是否失效
            if (errcode == 40014 || errcode == 42001) {
                // access_token 失效，重新获取并重试
                accessToken = refreshAccessToken();
                return sendAppMessage(accessToken, message); // 递归调用
            } else if (errcode == 0) {
                // 发送成功
                return "消息发送成功";
            } else {
                // 其他错误
                return "消息发送失败，错误码：" + errcode + "，错误信息：" + jsonResponse.getStr("errmsg");
            }
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            return "消息发送失败，异常信息：" + e.getMessage();
        }
    }

    /**
     * 获取access_token
     * @return
     */
    public String refreshAccessToken() {
        String corpid = "ww2a6d0aa844cc08ca";   //企业ID
        String corpsecret = "o2sywWtyH9puRLLc7IoYQYzDUtG6GCQMn-oLjotAkxE";    // 应用的凭证密钥
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
        try {
            // 发送 HTTP GET 请求
            String response = sendHttpGetRequest(url);
            // 解析返回的 JSON
            JSONObject jsonResponse = new JSONObject(response);
            String accessToken = jsonResponse.getStr("access_token");
            int expiresIn = jsonResponse.getInt("expires_in"); // 有效期，单位：秒

            // 保存新的 access_token 和过期时间
            saveAccessToken(accessToken, expiresIn);

            return accessToken;
        } catch (Exception e) {
            logger.info("刷新token异常：" + e.getMessage());
            return null;
        }
    }

    private String accessToken;
    private long expiresTime; // 过期时间戳（毫秒）

    public synchronized String getAccessToken() {
        // 检查 access_token 是否接近过期
        //过期时间提前5分钟就判定为失效 5 分钟是一个经验值，通常可以满足大多数场景的需求
        if (accessToken == null || System.currentTimeMillis() >= expiresTime - 5 * 60 * 1000) {
            refreshAccessToken();
        }
        return accessToken;
    }

    private void saveAccessToken(String accessToken, int expiresIn) {
        this.accessToken = accessToken;
        this.expiresTime = System.currentTimeMillis() + expiresIn * 1000;
    }

    /**
     * 发送企微消息通知文本
     * @param message
     * @param touser  接收短信的userid 中间’|’分隔
     */
    public void sendMessage(String message, String touser) {
        // 获取 access_token
        String accessToken = getAccessToken();
        Map<String, Object> sendContentMap = new HashMap<>();
        sendContentMap.put("touser", touser);
        sendContentMap.put("msgtype", "text");
        sendContentMap.put("agentid", 1000031);
        sendContentMap.put("safe", 0);
        sendContentMap.put("enable_id_trans", 0);
        sendContentMap.put("enable_duplicate_check", 1);

        Map<String, String> text = new HashMap<>();
        text.put("content", message);
        sendContentMap.put("text", text);

        // 发送应用消息
        String result = sendAppMessage(accessToken, JSONUtil.toJsonStr(sendContentMap));
        logger.info(result);
    }

    /**
     * 发送http请求 POST
     * @param url
     * @param message
     * @return
     */
    public String sendHttpPostRequest(String url, String message){
        HttpResponse response = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(message)
                .execute();
        String result = response.body();
        return result;
    }

    /**
     * 发送http请求 GET
     * @param url
     * @return
     */
    public String sendHttpGetRequest(String url){
        String response = HttpUtil.get(url);
        return response;
    }


}
